package com.joint.web.action.manage;

import com.fz.us.base.bean.BaseEnum;
import com.fz.us.base.bean.Pager;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.joint.base.bean.FlowEnum;
import com.joint.base.entity.Company;
import com.joint.base.entity.FileManage;
import com.joint.base.entity.Readers;
import com.joint.base.entity.Users;
import com.joint.base.exception.users.DutyNotExistsException;
import com.joint.base.exception.workflow.PcfgNotExistException;
import com.joint.base.service.*;
import com.joint.base.service.activiti.WorkflowService;
import com.joint.base.util.DataUtil;
import com.joint.core.entity.manage.MeetingRecord;
import com.joint.core.entity.manage.MeetingSign;
import com.joint.core.entity.manage.MeetingUse;
import com.joint.core.service.MeetingRecordService;
import com.joint.core.service.MeetingSignService;
import com.joint.core.service.MeetingUseService;
import com.joint.web.action.BaseFlowAction;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.ParentPackage;

import javax.annotation.Resource;
import java.util.*;


@ParentPackage("manage")
public class AjaxMeetingsignAction extends BaseFlowAction {
    @Resource
    private WorkflowService workflowService;
    @Resource
    private MeetingUseService meetingUseService;
    @Resource
    private MeetingSignService meetingSignService;
    @Resource
    private DepartmentService departmentService;
    @Resource
    private PostService postService;
    @Resource
    private PowerService powerService;
    @Resource
    private DutyService dutyService;
    @Resource
    private UsersService usersService;
    @Resource
    private ReadersService readersService;
    @Resource
    private TaskRecordService taskRecordService;

    /**
     * 会议室使用登记表(读)
     */
    private MeetingUse meetinguse;
    /**
     * 会议记录登记对象(读)
     */
    private MeetingSign meetingsign;
    /**
     * 登录人(读)
     */
    private Users loginUser;


    /**
     * 项目视图
     * @return
     */
    public String execute(){
        return "meetingsign";
    }



    public String list(){
        pager = new Pager();
        if (rows <= 0){
            rows = 10;
        }
        pager.setPageSize(rows);
        pager.setPageNumber(page);
        pager.setOrderBy("createDate");

        pager.setOrderType(BaseEnum.OrderType.desc);

        if(StringUtils.isNotEmpty(sidx)&& BaseEnum.OrderType.valueOf(sord)!=null){
            pager.setOrderBy(sidx);
            pager.setOrderType(BaseEnum.OrderType.valueOf(sord));
        }
        Company com = usersService.getCompanyByUser();
        Users user = usersService.getLoginInfo();

        Map<String,Object> params = new HashMap<String,Object>();
        params = getSearchFilterParams(_search,params,filters);
        //内嵌视图这里要加上
        if (StringUtils.isNotEmpty(parentId)){
            meetinguse = meetingUseService.get(parentId);
            params.put("meetingUse",meetinguse);
        }
        params.put("company",com);
        params.put("state",BaseEnum.StateEnum.Enable);

        //所有单子
        params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed, FlowEnum.ProcessState.Finished, FlowEnum.ProcessState.Deny});
        pager= meetingSignService.findByPagerAndLimit(true, "meetingsign", pager, params);

        List<MeetingSign>  meetingSignList;
        if (pager.getTotalCount() > 0){
            meetingSignList = (List<MeetingSign>) pager.getList();
        }else{
            meetingSignList = new ArrayList<>();
        }

        List<JSONObject> dataRows=new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;

        for(MeetingSign meetingSign: meetingSignList){
            rMap = new HashMap<String, Object>();
            rMap.put("id",meetingSign.getId());
            rMap.put("creater", meetingSign.getCreater() != null ? meetingSign.getCreater().getName() : "");
            rMap.put("createDate", DataUtil.DateToString(meetingSign.getCreateDate(), "yyyy-MM-dd"));
            rMap.put("state",meetingSign.getProcessState().value());
            JSONObject o = JSONObject.fromObject(rMap);
            dataRows.add(o);
        }
        data.put("dataRows",dataRows);
        data.put("page",page);
        data.put("rows",rows);
        long recordsNum = pager.getTotalCount();
        data.put("total",calcPageNum(recordsNum));
        data.put("records", recordsNum);
        return  ajaxJson(JSONObject.fromObject(data).toString());
    }


    public String read(){
        loginUser = usersService.getLoginInfo();
        if(StringUtils.isNotEmpty(keyId)) {
            meetingsign = meetingSignService.get(keyId);
            numStatus = workflowService.getNumStatus(keyId, loginUser);
            flowNumStatus = workflowService.getFlowNumStatus(keyId);


        }

        return "read";
    }



    private void setData(){
        if(StringUtils.isNotEmpty(keyId)){
            meetingsign = meetingSignService.get(keyId);
        }else{
            meetingsign  = new MeetingSign();
            meetingsign.setCreater(usersService.getLoginInfo());
        }

        if(StringUtils.isNotEmpty(parentId)){
            meetinguse = meetingUseService.get(parentId);
            meetingsign.setMeetingUse(meetinguse);
        }

        meetingsign.setCompany(usersService.getLoginInfo().getCompany());
    }

    // 保存
    public String save(){
        setData();
        try {
            if(StringUtils.isNotEmpty(keyId)){
                meetingSignService.update(meetingsign);
            } else {
                Map<String, Object> various = new HashMap<String, Object>();
                various.put("numStatus", 0);
                various.put("curDutyId", curDutyId);
                various.put("initDuty", curDutyId);
                meetingSignService.save(meetingsign, "meetingsign", various);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }

        return ajaxHtmlCallback("200", "保存成功！", "操作状态");
    }


    // 提交
    public String commit(){
        setData();
        Company company = usersService.getCompanyByUser();
        Map<String, Object> var1 = new HashMap<String, Object>();
        var1.put("numStatus", 0);
        var1.put("curDutyId", curDutyId);
        var1.put("initDuty", curDutyId);
        Map<String, Object> var2 = new HashMap<String, Object>();
        var2.put("numStatus", 1);
        var2.put("curDutyId", curDutyId);
        Set<Users> usersSet = Sets.newHashSet();
        Map<String, Object> map = new HashMap<String, Object>();

        meetinguse = meetingsign.getMeetingUse();
        if(meetinguse!=null && meetinguse.getJoinUsers() != null){
            for(Users users: meetinguse.getJoinUsers()){
                usersSet.add(users);
            }
        }


        try {
            if (StringUtils.isNotEmpty(keyId)) {
                meetingSignService.approve(meetingsign, FlowEnum.ProcessState.Finished, var2, curDutyId,comment);
            } else {
                keyId = meetingSignService.commit(meetingsign, FlowEnum.ProcessState.Finished, "meetingsign", var1, var2, curDutyId);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }
        //先删除读者
        readersService.deleteByKeyIdBussinessKey(keyId);
        //增加归档后读者
        for(Users users:usersSet){
            Readers readers = new Readers();
            readers.setUsers(users);
            readers.setBussinessKey("meetingsign");
            readers.setKeyId(keyId);
            readers.setType(2);
            readersService.save(readers);
        }
        return ajaxHtmlCallback("200", "签到成功！", "操作状态");
    }

    /**
     * 检验身份
     * @return
     */
    public String checkJoinUsers(){
        Users users = usersService.getLoginInfo();
        if(users == null){
            return ajaxHtmlCallback("400", "您没有操作此文档的权限", "操作状态");
        }
        if(StringUtils.isEmpty(parentId)){
            return ajaxHtmlCallback("400", "您没有操作此文档的权限", "操作状态");
        }
        List<MeetingSign> meetingSignList = meetingSignService.findDataByUsersParentId(users.getId(),parentId);
        if(meetingSignList.size()>0){
            return ajaxHtmlCallback("400", "您已对该会议进行了签到", "操作状态");
        }
        if(StringUtils.isNotEmpty(parentId)){
            MeetingUse meetingUse = meetingUseService.get(parentId);
            if(users != null && meetingUse.getJoinUsers() != null){
                for(Users users1: meetingUse.getJoinUsers()){
                    if(StringUtils.equals(users.getId(),users1.getId())){
                        return ajaxHtmlCallback("200", "签到成功", "操作状态");
                    }
                }
            }
        }
        return ajaxHtmlCallback("400", "您没有操作此文档的权限", "操作状态");
    }

    public MeetingUse getMeetinguse() {
        return meetinguse;
    }

    public void setMeetinguse(MeetingUse meetinguse) {
        this.meetinguse = meetinguse;
    }

    public MeetingSign getMeetingsign() {
        return meetingsign;
    }

    public void setMeetingsign(MeetingSign meetingsign) {
        this.meetingsign = meetingsign;
    }

    public Users getLoginUser() {
        return loginUser;
    }

    public void setLoginUser(Users loginUser) {
        this.loginUser = loginUser;
    }
}

